﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Payroll.BusinessLogic;
using Payroll.Common.Utils;
using Payroll.Common.Utils.Html;
using PayrollHR.Web;
using Payroll.BusinessLogic.CustomerManager;
using Payroll.BusinessLogic.Directory;
using Payroll.BusinessLogic.Utils;
using Payroll.BusinessLogic.ExportImport;
using MigraDoc.DocumentObjectModel;

namespace PayrollHR.Administration.Modules
{
    public partial class CustomersControl : BasePayrollAdministrationUserControl
    {
        private const string m_filetemplate = "CustomerList.xlsx";
        private const int m_pageSize = 50;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                LoadGrid();
            }
        }
        protected void BindGrid()
        {
            var customers = GetCustomers();
            gvCustomers.DataSource = customers;
            gvCustomers.DataBind();
        }
        protected void LoadGrid()
        {
            var customers = LoadCustomers();
            gvCustomers.DataSource = customers;
            gvCustomers.DataBind();
        }
        protected List<Customer> GetCustomers()
        {
            CustomerSearchResult customerColection = ctrCustomerSearch.GetCustomerSearch();
            List<Customer> customer = CustomerService.GetAllCustomer(customerColection,  m_pageSize);
            return customer;
        }
        protected List<Customer> LoadCustomers()
        {
            int Useid = PayrollContext.Current.Session.EmployeeId;
            CustomerSearchResult customerColection = new CustomerSearchResult
            {
                CustName = "",
                CustCaseWork = "",
                CustHour = "",
                CustMobile = "",
                CustYearOfBirth = "",
                CustMonthOfBirth = "",
                CustParent = "",
                IsStudy = 4,
                CustNationalId = 0,
                CustCounselor = "",
                CutomerTypeId = 0,
                statusVisa = 6,
                CustSchool = "",
                ProCurator = "",
                CustYear = 0,
                CustMonth = 0,
                UserId = Useid
            };
            var cust = this.CustomerService.GetCustomerSearchResultbyId(Useid);
            if (!CommonHelper.IsNull(cust))
            {
                customerColection = cust;
            }
            List<Customer> customer = CustomerService.GetAllCustomer(customerColection, m_pageSize);
            return customer;
        }
        protected void gvCustomers_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvCustomers.PageIndex = e.NewPageIndex;
            BindGrid();
        }
        #region btn
        protected void SearchButton_Click(object sender, EventArgs e)
        {
            this.BindGrid();
        }
        protected void btnExportXLS_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    string fileName = string.Format("CustomerList_{0}_{1}.xlsx", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"), CommonHelper.GenerateRandomDigitCode(4));
                    string filePath = string.Format("{0}Administration\\FileExport\\{1}", HttpContext.Current.Request.PhysicalApplicationPath, fileName);
                    string fileTeamplate = string.Format("{0}Files\\Template\\{1}", HttpContext.Current.Request.PhysicalApplicationPath, m_filetemplate);
                    CustomerSearchResult customerColection = ctrCustomerSearch.GetCustomerSearch();
                    List<Customer> customer = CustomerService.GetAllCustomer(customerColection);
                    ExcelHelper.ExportCustomerToExcel(customer, ref filePath, fileTeamplate);
                    hlexport.Visible = true;
                    hlexport.Text = "Save As File Export";
                    hlexport.NavigateUrl = "../FileExport/" + fileName;
                }
                catch (Exception exc)
                {
                    ProcessException(exc);
                }
            }
        }
        protected void btnToPdf_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    CustomerSearchResult customerColection = ctrCustomerSearch.GetCustomerSearch();
                    List<Customer> customer = CustomerService.GetAllCustomer(customerColection);
                    string fileName = string.Format("products_{0}_{1}.pdf", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"), CommonHelper.GenerateRandomDigitCode(4));
                    string filePath = string.Format("{0}Administration\\FileExport\\{1}", HttpContext.Current.Request.PhysicalApplicationPath, fileName);

                    PDFHelper.PrintCustomerToPdf(customer, filePath);
                    hlexport.Visible = true;
                    hlexport.Text = "Save As File Export";
                    hlexport.NavigateUrl = "../FileExport/" + fileName;
                }
                catch (Exception exc)
                {
                    ProcessException(exc);
                }
            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    List<int> customerColection = new List<int>();
                    foreach (GridViewRow row in gvCustomers.Rows)
                    {
                        CheckBox cbCustomerInfo = row.FindControl("cbCustomerInfo") as CheckBox;
                        HiddenField hfCustomerID = row.FindControl("hfCustomerID") as HiddenField;
                        int CustomerID = int.Parse(hfCustomerID.Value);
                        if (cbCustomerInfo.Checked)
                        {
                            customerColection.Add(CustomerID);
                        }
                    }
                    if (customerColection.Count > 0)
                    {
                        this.CustomerService.Delete(customerColection);
                        this.BindGrid();
                    }
                }
                catch (Exception exc)
                {
                    ProcessException(exc);
                }
            }
        }
        protected void gvCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Button btnPrint = e.Row.FindControl("btnPrint") as Button;
                if (btnPrint != null)
                    btnPrint.CommandArgument = e.Row.RowIndex.ToString();
            }
        }
        protected void gvCustomers_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName.Equals("Print"))
                {
                    int index = Convert.ToInt32(e.CommandArgument);
                    GridViewRow row = gvCustomers.Rows[index];
                    HiddenField hfCustomerID = row.FindControl("hfCustomerID") as HiddenField;
                    int CustomerID = int.Parse(hfCustomerID.Value);
                    string fileName = string.Format("customer_{0}_{1}.pdf", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"), CommonHelper.GenerateRandomDigitCode(4));
                    string filePath = string.Format("{0}Administration\\FileExport\\{1}", HttpContext.Current.Request.PhysicalApplicationPath, fileName);
                    Customer customer = this.CustomerService.GetCustomerById(CustomerID);
                    List<ProfileProperty> listProfileSupport = CustomerService.GetAllProfilePropertyByCustomerId(CustomerID);
                    List<profile> listProfileStudy = CustomerService.GetAllProfileByCustomerID(CustomerID, 5);
                    List<profile> listProfilePersonal = CustomerService.GetAllProfileByCustomerID(CustomerID, 4);
                    List<profile> listProfileFinan = CustomerService.GetAllProfileByCustomerID(CustomerID, 6);
                    List<profile> listProfileProperty = CustomerService.GetAllProfileByCustomerID(CustomerID, 7);
                    List<ProfileFinan> listProfileFinanSource = CustomerService.GetAllByCustomerId(CustomerID);
                    List<FeesSchedule> listProfileFeesShedule = CustomerService.GetAllFeesScheduleByCustomerId(CustomerID);
                    string fileImage = string.Format("{0}images\\LogoOsiVietNam.jpg", HttpContext.Current.Request.PhysicalApplicationPath);
                    Document doc = PDFHelper.PrintCustomerToPdf(customer, listProfileFeesShedule, fileImage, fileImage);
                    doc = PDFHelper.PrintCaseProfilePersonal(doc, listProfilePersonal, customer);
                    doc = PDFHelper.PrintCaseProfileStudy(doc, listProfileStudy, customer);
                    doc = PDFHelper.PrintCaseProfileFinan(doc, listProfileFinan, customer);
                    doc = PDFHelper.PrintCaseProfileProperty(doc, listProfileProperty, customer);
                    doc = PDFHelper.PrintCaseProfileFinanSource(doc, listProfileFinanSource);
                    doc = PDFHelper.PrintCaseProfileSupport(doc, listProfileSupport);
                    doc = PDFHelper.PrintCaseProfileFeesShedule(doc, listProfileFeesShedule);
                    PDFHelper.PrintFile(doc, filePath);
                    hlexport.Visible = true;
                    hlexport.Text = "Save As File Print";
                    hlexport.NavigateUrl = "../FileExport/" + fileName;
                }
            }
            catch (Exception exc)
            {
                ProcessException(exc);
            }
        }
        #endregion
    }
}